import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yi_shop/model/product.dart';
import 'package:yi_shop/route/index.dart';
import 'package:yi_shop/ui/scroll_refresh_config.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/tools.dart';

class GroupOrderController extends GetxController {
  RxList<SpellOrderProductModel> pageList = RxList([]);

  RefreshController refreshController = RefreshController();

  RxInt total = 45.obs;

  @override
  void onInit() {
    initData();
    super.onInit();
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(SpellOrderProductModel(
          avatar:
              'https://img0.baidu.com/it/u=4130322821,3017185594&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
          nickname: '李四',
          price: 100.0 + r.nextInt(500),
          spellCount: r.nextInt(50),
          differCount: r.nextInt(20),
          residueTime: '${r.nextInt(23)}:${r.nextInt(59)}:${r.nextInt(59)}'));
    }
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > total.value) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    initData();

    /// 完毕
    refreshController.loadComplete();
  }
}

class GroupOrderPage extends GetView<GroupOrderController> {
  const GroupOrderPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: ToolsUtils.builderLeading(),
        title: const Text('拼团列表'),
        bottom: PreferredSize(
            preferredSize: const Size.fromHeight(40),
            child: Container(
              height: 40,
              decoration:
                  BoxDecoration(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2)),
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 15.w),
              child: Obx(() => Text(
                    '已有${controller.total.value}人发起拼单',
                    style:
                        StylesUtils.textStyle(color: ColorsUtils.rgba(0, 0, 0, 0.647058823529412)),
                  )),
            )),
      ),
      body: Obx(() => scrollRefreshConfig(context)),
    );
  }

  ScrollRefreshConfig scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: listViewBuilder(context),
    );
  }

  ListView listViewBuilder(BuildContext context) {
    return ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        final row = controller.pageList[index];
        return Container(
          padding: EdgeInsets.only(
              left: 15.w,
              right: 10.w,
              top: 15.h,
              bottom: index < controller.pageList.length - 1 ? 0 : 20.h),
          decoration: const BoxDecoration(color: Colors.white),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5.w),
                child: CircleAvatar(
                  radius: 20,
                  backgroundImage: NetworkImage(row.avatar),
                ),
              ),
              Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      row.nickname,
                      style: StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10.w),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '￥${row.price}',
                      style: StylesUtils.customTextStyle(
                          color: ColorsUtils.colorE419, fontSize: StylesUtils.fontSize13),
                    ),
                  )
                ],
              ),
              Expanded(
                  child: Container(
                padding: EdgeInsets.only(right: 10.w),
                child: Column(
                  children: [
                    Container(
                      alignment: Alignment.centerRight,
                      child: Text.rich(TextSpan(
                          style: StylesUtils.customTextStyle(
                              color: ColorsUtils.color2a2a, fontSize: StylesUtils.fontSize13),
                          children: [
                            TextSpan(text: '${row.spellCount}人，还差'),
                            TextSpan(
                                text: '${row.differCount}人',
                                style: StylesUtils.customTextStyle(
                                    fontSize: StylesUtils.fontSize13,
                                    color: ColorsUtils.colorE419)),
                            const TextSpan(text: '拼成')
                          ])),
                    ),
                    Container(
                      alignment: Alignment.centerRight,
                      margin: EdgeInsets.only(top: 10.w),
                      child: Text(
                        '剩余 ${row.residueTime}',
                        style: StylesUtils.textStyle(
                            color: ColorsUtils.rgba(0, 0, 0, 0.447058823529412),
                            fontSize: StylesUtils.fontSize13),
                      ),
                    )
                  ],
                ),
              )),
              Center(
                child: Container(
                  constraints: const BoxConstraints.tightFor(width: 94, height: 35),
                  child: TextButton(
                      onPressed: () {
                        Get.toNamed(RoutePath.groupConfirm);
                      },
                      style: ButtonStyle(
                          minimumSize: const MaterialStatePropertyAll(Size.infinite),
                          padding: const MaterialStatePropertyAll(EdgeInsets.zero),
                          shape: MaterialStatePropertyAll(
                            RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.r)),
                          ),
                          backgroundColor: MaterialStatePropertyAll(
                              ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)),
                          alignment: Alignment.center),
                      child: Text(
                        '去拼单',
                        style: StylesUtils.customTextStyle(),
                      )),
                ),
              )
            ],
          ),
        );
      },
      itemCount: controller.pageList.length,
    );
  }
}
